//
//  HomeSmallVideoController.m
//  OnionHome
//
//  Created by fengjie on 2019/9/18.
//  Copyright © 2019 FengJie. All rights reserved.
//

#import "HomeSmallVideoController.h"

#import "CLPlayerView.h"
#import "SmallVideoDetailController.h"

@interface HomeSmallVideoController ()<UICollectionViewDelegate,UICollectionViewDataSource,CLCollectionViewCellDelegate, UIScrollViewDelegate>
/**<#属性#>*/
@property (nonatomic,strong)UICollectionView*listView;
/**<#属性#>*/
@property (nonatomic,strong) UICollectionViewFlowLayout * layout;
/**数据源*/
@property (nonatomic,strong)NSMutableArray*dataArray;

/**CLplayer*/
@property (nonatomic, weak) CLPlayerView *playerView;
/**记录Cell*/
@property (nonatomic, assign) UICollectionViewCell *cell;

@end

@implementation HomeSmallVideoController

- (void)viewDidLoad{
    [super viewDidLoad];
    [self.view addSubview:self.listView];
    
    [self.listView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(0);
    }];
}
#pragma mark ---UICollectionViewDelegate,UICollectionViewDataSource
-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return 1;
}
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return self.dataArray.count;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    HomeSmallVideoCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:NSStringFromClass(HomeSmallVideoCell.class) forIndexPath:indexPath];
//    cell.delegate = self;
//    cell.model = self.dataArray[indexPath.row];
    kWeakSelf(weakSelf);
    cell.tapBlock = ^{
        [weakSelf pushDetailController:indexPath];
    };
    return cell;
}
//cell将要出现的时候调用
-(void)collectionView:(UICollectionView *)collectionView willDisplayCell:(UICollectionViewCell *)cell forItemAtIndexPath:(NSIndexPath *)indexPath{
    HomeSmallVideoCell * myCell = (HomeSmallVideoCell *)cell;
    myCell.model = self.dataArray[indexPath.row];

}
//cell离开tableView时调用
-(void)collectionView:(UICollectionView *)collectionView didEndDisplayingCell:(UICollectionViewCell *)cell forItemAtIndexPath:(NSIndexPath *)indexPath{
    //因为复用，同一个cell可能会走多次
    if ([_cell isEqual:cell]) {
        //区分是否是播放器所在cell,销毁时将指针置空
        [_playerView destroyPlayer];
        _cell = nil;
    }
}
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    [self pushDetailController:indexPath];
}
-(void)pushDetailController:(NSIndexPath *)indexpath{
    SmallVideoDetailController * vc = [SmallVideoDetailController new];
    vc.indexxPath = indexpath;
    vc.dataArray = self.dataArray;
    [self.navigationController presentViewController:[[BasseNavigationController alloc]initWithRootViewController:vc] animated:YES completion:nil];

}
#pragma mark  定义每个cell的大小
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    CGFloat width = (KScreenWidth - 4)/2;
    return CGSizeMake(width,  width * 1.7 );
}
// 列间距
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section{
    return 0;
}
// 行间距
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section{
    return 4;
}
#pragma mark - 点击播放代理
-(void)cl_tableViewCellPlayVideoWithCell:(HomeSmallVideoCell *)cell{
    //记录被点击的Cell
    _cell = cell;
    //销毁播放器
    [_playerView destroyPlayer];
    CLPlayerView *playerView = [[CLPlayerView alloc] initWithFrame:CGRectZero];
    _playerView = playerView;
    [cell.playerBgView addSubview:_playerView];
    [playerView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(0);
    }];
    //    //重复播放，默认不播放
    //    _playerView.repeatPlay = YES;
    //    //当前控制器是否支持旋转，当前页面支持旋转的时候需要设置，告知播放器
//        _playerView.isLandscape = YES;
    //    //设置等比例全屏拉伸，多余部分会被剪切
    //    _playerView.fillMode = ResizeAspectFill;
    //设置进度条背景颜色
    _playerView.progressBackgroundColor = [UIColor colorWithRed:53 / 255.0 green:53 / 255.0 blue:65 / 255.0 alpha:1];
    //设置进度条缓冲颜色
    _playerView.progressBufferColor = [UIColor grayColor];
    //设置进度条播放完成颜色
    _playerView.progressPlayFinishColor = UIColorFromRGB(0x009966);
    //    //全屏是否隐藏状态栏
//        _playerView.fullStatusBarHidden = NO;
    //    //转子颜色
    //    _playerView.strokeColor = [UIColor redColor];
    //视频地址
    _playerView.url = [NSURL URLWithString:cell.model.videoUrl];
    //播放
    [_playerView playVideo];
    //返回按钮点击事件回调
    [_playerView destroyPlay:^{
        cell.stopPlay = YES;
        DLog(@"播放器被销毁了");
    }];
    [_playerView backButton:^(UIButton *button) {
        DLog(@"返回按钮被点击");
    }];
    //播放完成回调
    kWeakSelf(weakSelf);
    [_playerView endPlay:^{
        //销毁播放器
        [weakSelf.playerView destroyPlayer];
        weakSelf.playerView = nil;
        weakSelf.cell = nil;
        DLog(@"播放完成");
    }];

}
#pragma mark ---懒加载
-(UICollectionView *)listView{
    if (!_listView) {
        self.layout= [[UICollectionViewFlowLayout alloc] init];
        _listView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:self.layout];
        _listView.backgroundColor=KWhiteColor;
        _listView.delegate=self;
        _listView.dataSource = self;
        _listView.scrollEnabled = YES;
        [_listView registerClass:[HomeSmallVideoCell class] forCellWithReuseIdentifier:NSStringFromClass(HomeSmallVideoCell.class)];
        
    }
    return _listView;
}
-(NSMutableArray *)dataArray{
    if (!_dataArray) {
        _dataArray = [[NSMutableArray alloc] init];
        NSData *JSONData = [NSData dataWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"XSPDate" ofType:@"json"]];
        NSArray *array = [NSJSONSerialization JSONObjectWithData:JSONData options:NSJSONReadingAllowFragments error:nil];
        [array enumerateObjectsUsingBlock:^(NSDictionary * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            PlayModel *model = [PlayModel new];
            [model setValuesForKeysWithDictionary:obj];
            [_dataArray addObject:model];
        }];
    }
    return _dataArray;
}


@end

#pragma mark ---HomeSmallVideoCell

@interface HomeSmallVideoCell ()
/**视频图片*/
@property (nonatomic,strong)UIImageView * IMGView;
/**标题*/
@property (nonatomic,strong)UILabel * titleLabel;
/**播放按钮*/
@property (nonatomic,strong)UIButton * stopBtn;
/**点赞数量*/
@property (nonatomic,strong)UILabel * rightLabel;
@end

@implementation HomeSmallVideoCell

-(instancetype)initWithFrame:(CGRect)frame{
    self = [super initWithFrame:frame];
    if (self) {
        [self createUI];
    }
    return self;
}
-(void)createUI{
    
    UIView * maskeView = UIView.new;
    maskeView.backgroundColor = RGBA(39, 51, 35, 0.3);
    maskeView.userInteractionEnabled = YES;

    
    self.IMGView = UIImageView.new;
    self.IMGView.userInteractionEnabled = YES;
    
    self.playerBgView = UIView.new;
    self.playerBgView.userInteractionEnabled = YES;
    self.playerBgView.hidden = YES;

    [self addSubview:self.IMGView];
    [self addSubview:self.playerBgView];

    [self.IMGView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(0);
    }];
    
    [self.playerBgView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.top.right.bottom.mas_equalTo(self.IMGView);
    }];

    self.titleLabel = UILabel.new;
    self.titleLabel.textColor = UIColorFromRGB(0xFFFFFF);
    self.titleLabel.font = PingFangSC_Medium(16);
    self.titleLabel.text = @"教你做美味沙拉酱";
    self.titleLabel.userInteractionEnabled = YES;
    
    self.stopBtn = UIButton.new;
    [self.stopBtn setTitle:@"12万次播放" forState:UIControlStateNormal];
    [self.stopBtn setImage:IMAGE_NAMED(@"xiao_video_play") forState:UIControlStateNormal];
    [self.stopBtn setTitleColor:UIColorFromRGB(0xF5F7F5) forState:UIControlStateNormal];
    self.stopBtn.titleLabel.font = PingFangSC_Medium(11);
    self.stopBtn.userInteractionEnabled = YES;
    
    kWeakSelf(weakSelf);
    [self.stopBtn addActionHandler:^{
//        weakSelf.playerBgView.hidden = NO;
//        [weakSelf playAction];
        BlockSafeRun(weakSelf.tapBlock);
    }];

    self.rightLabel = UILabel.new;
    self.rightLabel.textColor = UIColorFromRGB(0xF5F7F5);
    self.rightLabel.font = PingFangSC_Medium(11);
    self.rightLabel.text = @"14.2万赞";
    
    [self.IMGView addSubview:maskeView];
    
    [maskeView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(0);
    }];
    
    
    [maskeView addSubview:self.titleLabel];
    [maskeView addSubview:self.stopBtn];
    [maskeView addSubview:self.rightLabel];
    
    [self.stopBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(16);
        make.bottom.mas_equalTo(-16);
    }];
    [self.rightLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(-16);
        make.centerY.mas_equalTo(self.stopBtn);
    }];
    
    [self.titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(16);
        make.bottom.mas_equalTo(self.stopBtn.mas_top).offset(-16);
        make.right.mas_equalTo(-16);
    }];


}
-(void)setModel:(PlayModel *)model{
    _model = model;
    [self.IMGView imageViewWithUrl:model.pictureUrl placeholderImage:@"dynamicDefut"];
}
- (void)setStopPlay:(BOOL)stopPlay{
    _stopPlay = stopPlay;
    self.playerBgView.hidden = stopPlay;
}
- (void)playAction {
    
    if (_delegate && [_delegate respondsToSelector:@selector(cl_tableViewCellPlayVideoWithCell:)]){
        [_delegate cl_tableViewCellPlayVideoWithCell:self];
    }
}


@end
